package com.wwf;

import com.wwf.util.JSONSerializer;
import com.wwf.util.RpcDecode;
import com.wwf.util.RpcEncode;
import com.wwf.util.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author wwf
 * @date 2021年01月07日 13:57:08
 */
public class RPCConumer {
    /**
     * 创建当前cpu可用核数的线程池
     */
    private  ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    private static  UserClientHandler userClientHandler;

    public Object creatProxy(final Class<?> serviceClass, final RpcRequest rpcRequest){
        Object o = Proxy.newProxyInstance(RPCConumer.class.getClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if(userClientHandler == null) initClient();
                rpcRequest.setClassName(serviceClass.getSimpleName());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setParameterTypes(method.getParameterTypes());
                rpcRequest.setParameters(args);
                rpcRequest.setRequestid("userServiceImpl");
                userClientHandler.setPara(rpcRequest);
                return service.submit(userClientHandler).get();
            }
        });
        return  o;
    }

    private static void initClient(){
         userClientHandler = new UserClientHandler();
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap = bootstrap.group(eventExecutors);
        bootstrap.channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new RpcEncode(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(userClientHandler);
                    }
                });
        try {
            bootstrap.connect("127.0.0.1",8087).sync();
        } catch (InterruptedException exception) {
            exception.printStackTrace();
        }
    }
}
